package me.ivps.android.servicedemo.service;

import java.util.Date;

import me.ivps.android.servicedemo.MainApp;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class MainService extends Service {
    
    private static final String TAG = "MainService";
    
    private final MyBinder myBinder = new MyBinder();
    
    public class MyBinder extends Binder {
        
        public MainService getService() {
            return MainService.this;
        }
    }
    
    private MainApp mApp;
    
    private UpdateThread mThread;
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");
        mApp = (MainApp) getApplication();
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
        mApp = (MainApp) getApplication();
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind");
        return myBinder;
    }
    
    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "onUnbind");
        return super.onUnbind(intent);
    }
    
    public void startUpdate() {
        Log.d(TAG, "onStartUpdate");
        if (mThread != null) {
            mThread.interrupt();
            mThread = null;
        }
        mThread = new UpdateThread();
        mThread.start();
    }
    
    public void stopUpdate() {
        Log.d(TAG, "onStopUpdate");
        if (mThread != null) {
            mThread.interrupt();
            mThread = null;
        }
    }
    
    class UpdateThread extends Thread {
        
        @Override
        public void run() {
            Log.d(TAG, "Start Update");
            while (!interrupted()) {
                Log.d(TAG, "Generate New String");
                mApp.addText(new Date().toString());
                try {
                    Thread.sleep(2000L);
                }
                catch (InterruptedException e) {
                    Log.e(TAG, "Thread Error", e);
                    interrupt();
                }
            }
            Log.d(TAG, "Stop Update");
        }
    }
    
}
